<template>
  <div class="lc_wrap">
    <el-row class="userManage">
      <!-- 左侧树 -->
      <el-col :span="leftWidth">
        <div class="box">
          <el-scrollbar>
            <basic-container>
              <avue-tree
                :option="treeOption"
                :data="treeData"
                @node-click="nodeClick"/>
            </basic-container>
          </el-scrollbar>
        </div>
      </el-col>

      <!-- 表格内容 -->
      <el-col :span="rightWidth">
        <basic-container>
          <avue-crud
            :option="option"
            :search.sync="search"
            :table-loading="loading"
            :data="data"
            ref="crud"
            v-model="form"
            :permission="permissionList"
            @row-del="rowDel"
            @row-update="rowUpdate"
            @row-save="rowSave"
            :before-open="beforeOpen"
            :page.sync="page"
            @search-change="searchChange"
            @search-reset="searchReset"
            @selection-change="selectionChange"
            @current-change="currentChange"
            @size-change="sizeChange"
            @refresh-change="refreshChange"
            @on-load="onLoad"
          >

            <!-- 左上方菜单 -->
            <template slot="menuLeft">
              <el-button
                type="danger"
                size="small"
                plain
                icon="el-icon-delete"
                v-if="permission.user_delete"
                @click="handleDelete">
                删 除
              </el-button>

              <el-button
                type="info"
                size="small"
                plain
                v-if="permission.user_role"
                icon="el-icon-user"
                @click="handleGrant">
                角色配置
              </el-button>

              <el-button
                type="info"
                size="small"
                plain
                v-if="permission.user_reset"
                icon="el-icon-refresh"
                @click="handleReset">
                密码重置
              </el-button>

              <el-button
                type="info"
                size="small"
                plain
                v-if="userInfo.role_name.includes('admin')"
                icon="el-icon-setting"
                @click="handlePlatform">
                平台配置
              </el-button>

              <el-button
                type="success"
                size="small"
                plain
                v-if="userInfo.role_name.includes('admin')"
                icon="el-icon-upload2"
                @click="handleImport">
                导 入
              </el-button>

              <el-button
                type="warning"
                size="small"
                plain
                v-if="userInfo.role_name.includes('admin')"
                icon="el-icon-download"
                @click="handleExport">
                导 出
              </el-button>

              <el-button
                type="success"
                size="small"
                plain
                v-if="userInfo.role_name.includes('admin')"
                icon="el-icon-download"
                @click="handleExportArchives">
                导出个人档案
              </el-button>

              <el-button
                type="danger"
                size="small"
                plain
                v-if="userInfo.role_name.includes('admin')"
                icon="el-icon-s-release"
                @click="handleLeaveJob">
                离 职
              </el-button>

              <el-button
                type="success"
                size="small"
                plain
                v-if="userInfo.role_name.includes('admin')"
                icon="el-icon-refresh-left"
                @click="handleRefreshJob">
                恢 复
              </el-button>
            </template>

            <!-- 人员状态表格自定义 -->
            <template slot="ryzt" slot-scope="scope">
              <div>
                <el-tag v-if="scope.row['ryzt'] === 1" type="success">{{ryztObj[scope.row['ryzt']]}}</el-tag>
                <el-tag v-else type="danger">{{ryztObj[scope.row['ryzt']]}}</el-tag>
              </div>
            </template>

            <!-- 二维码表格自定义 -->
            <template slot="ewm" slot-scope="scope">
              <div>
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-picture-outline"
                  v-if="scope.row['ewm'] === 0 || scope.row['ewm'] === -1 || scope.row['ewm'] === '' || scope.row['ewm'] === undefined" @click="generateQRCode(scope.row['id'])">
                  生成二维码
                </el-button>

                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-view"
                  v-else
                  @click="handleViewQRCode(scope.row)">
                  查 看
                </el-button>
              </div>
            </template>

            <!-- 工卡表格自定义 -->
            <template slot="gkContent" slot-scope="scope">
              <div>
                <span v-if=" scope.row['gk'] === -1 || scope.row['gk'] === '' || scope.row['gk'] === undefined">-</span>
                <span v-else>{{ locationCardObj[scope.row["gk"]] }}</span>
              </div>
            </template>

            <!-- 电量表格自定义 -->
            <template slot="power" slot-scope="scope">
              <div>
                <span v-if="scope.row['power'] === '' || scope.row['power'] === undefined || scope.row['power'] < 0">-</span>
                <span v-else>{{ scope.row["power"] }}%</span>
              </div>
            </template>

            <!-- 绑卡表格自定义 -->
            <template slot="bindCard" slot-scope="scope">
              <div>
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-postcard"
                  :disabled=" scope.row['gk'] !== -1 && scope.row['gk'] !== '' && scope.row['gk'] !== undefined" @click="handleBindGK(scope.row['id'])">
                  绑定工卡
                </el-button>
              </div>
            </template>

            <!-- 照片表单自定义 -->
            <template slot="zpForm">
              <div class="zp_content">
                <el-upload
                  v-if="dialogType !== 'view'"
                  accept="image/*"
                  action="/api/fileManager/upload/file"
                  :headers="SetHeaders"
                  :file-list="zpFileList"
                  :before-upload="beforeUploadZP"
                  :on-success="uploadZPSuccess"
                >
                  <el-button size="small" type="primary" icon="el-icon-picture">选择照片</el-button>
                </el-upload>

                <el-tag
                  v-for="(item, index) in zpFileList"
                  :key="index"
                  type="info"
                  :closable="dialogType !== 'view'"
                  @close="handleRemoveZP(index)"
                >
                  <img
                    :src="item.response.data.fileUrl"
                    @click="previewZP(item)"
                    alt
                  />
                </el-tag>
              </div>
            </template>

            <!-- 学历证书表单自定义 -->
            <template slot="xlzsForm">
              <div class="xlzs_content">
                <el-upload
                  v-if="dialogType !== 'view'"
                  accept="image/*"
                  action="/api/fileManager/upload/file"
                  :headers="SetHeaders"
                  :file-list="xlzsFileList"
                  :before-upload="beforeUploadXLZS"
                  :on-success="uploadXLZSSuccess"
                >
                  <el-button size="small" type="primary" icon="el-icon-picture">选择图片</el-button>
                </el-upload>

                <el-tag
                  v-for="(item, index) in xlzsFileList"
                  :key="index"
                  type="info"
                  :closable="dialogType !== 'view'"
                  @close="handleRemoveXLZS(index)"
                >
                  <img
                    :src="item.response.data.fileUrl"
                    @click="previewXLZS(item)"
                    alt
                  />
                </el-tag>
              </div>
            </template>

            <!-- 附件表单自定义 -->
            <template slot="fjForm">
              <div>
                <el-upload
                  v-if="dialogType !== 'view'"
                  action="/api/fileManager/upload/file"
                  :headers="SetHeaders"
                  :file-list="fjFileList"
                  :before-upload="beforeUploadFJ"
                  :on-remove="handleRemoveFJ"
                  :on-success="uploadFJSuccess"
                >
                  <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
                </el-upload>

                <a
                  v-else
                  v-for="(item, index) in fjFileList"
                  :key="index"
                  :href="downloadHead + item.response.data.id"
                  style="color:#409EFF"
                >
                  <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
                </a>
              </div>
            </template>

            <!-- 工作简历表单自定义 -->
            <template slot="gzjl2Form">
              <div>
                <el-upload
                  v-if="dialogType !== 'view'"
                  action="/api/fileManager/upload/file"
                  :headers="SetHeaders"
                  :file-list="gzjlFileList"
                  :before-upload="beforeUploadGZJL"
                  :on-remove="handleRemoveGZJL"
                  :on-success="uploadGZJLSuccess"
                >
                  <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
                </el-upload>

                <a
                  v-else
                  v-for="(item, index) in gzjlFileList"
                  :key="index"
                  :href="downloadHead + item.response.data.id"
                  style="color:#409EFF"
                >
                  <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
                </a>
              </div>
            </template>
          </avue-crud>

          <!-- 角色配置弹窗 -->
          <el-dialog
            title="用户角色配置"
            append-to-body
            :visible.sync="roleBox"
            width="345px"
          >
            <el-tree
              :data="roleGrantList"
              show-checkbox
              check-strictly
              default-expand-all
              node-key="id"
              ref="treeRole"
              :default-checked-keys="roleTreeObj"
              :props="props">
            </el-tree>

            <span slot="footer" class="dialog-footer">
              <el-button @click="roleBox = false">取 消</el-button>
              <el-button type="primary" @click="submitRole">确 定</el-button>
            </span>
          </el-dialog>

          <!-- 导入用户数据弹窗 -->
          <el-dialog
            title="用户数据导入"
            append-to-body
            :visible.sync="excelBox"
            width="555px"
          >
            <avue-form
              :option="excelOption"
              v-model="excelForm"
              :upload-after="uploadAfter"
            >
              <template slot="excelTemplate">
                <el-button type="primary" @click="handleTemplate">
                  点击下载<i class="el-icon-download el-icon--right"></i>
                </el-button>
              </template>
            </avue-form>
          </el-dialog>

          <!-- 配台配置弹窗 -->
          <el-dialog
            title="用户平台配置"
            append-to-body
            :visible.sync="platformBox"
          >
            <avue-crud
              :option="platformOption"
              :table-loading="platformLoading"
              :data="platformData"
              ref="platformCrud"
              v-model="platformForm"
              :before-open="platformBeforeOpen"
              :page.sync="platformPage"
              :permission="platformPermissionList"
              @row-update="platformRowUpdate"
              @search-change="platformSearchChange"
              @search-reset="platformSearchReset"
              @selection-change="platformSelectionChange"
              @current-change="platformCurrentChange"
              @size-change="platformSizeChange"
              @refresh-change="platformRefreshChange"
              @on-load="platformOnLoad"
            >
              <template slot-scope="{ row }" slot="tenantName">
                <el-tag>{{ row.tenantName }}</el-tag>
              </template>
              <template slot-scope="{ row }" slot="userTypeName">
                <el-tag>{{ row.userTypeName }}</el-tag>
              </template>
            </avue-crud>
          </el-dialog>

          <!-- 弹窗：图片 -->
          <viewpicture
            :localPicBox="localPicBox"
            :localPictures="localPictures"
            :viewPicTitle="viewPicTitle"
            @confirmViewPicture="confirmViewPicture"
            @handleClosePicBox="handleClosePicBox">
          </viewpicture>

          <!-- 绑定工卡弹窗 -->
          <el-dialog
            title="绑定工卡"
            append-to-body
            :visible.sync="bindLocationCardDialog"
            :close-on-click-modal="false"
            :before-close="closeBindLocationCardDialog"
            width="60%"
          >
            <!-- 内容 -->
            <el-form
              :model="bindForm"
              :rules="bindRules"
              ref="bindForm"
              class="bind_gk_form"
            >
              <el-form-item label="工卡号" prop="gk">
                <el-select
                  v-model="bindForm.gk"
                  placeholder="请选择 工卡号"
                  size="small"
                  class="gk_select"
                  clearable
                >
                  <el-option
                    v-for="item in locationCards"
                    :key="item.value"
                    :label="item.bqh"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>

            <!-- 按钮 -->
            <div class="bind_card_footer">
              <el-button
                type="primary"
                size="small"
                @click="bindLocationCard()">
                绑 定
              </el-button>
              <el-button size="small" @click="closeBindLocationCardDialog()">
                取 消
              </el-button>
            </div>
          </el-dialog>
        </basic-container>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getList,
  getUser,
  getUserPlatform,
  remove,
  update,
  updatePlatform,
  add,
  grant,
  resetPassword,
  updateUserStatus,
  bindLocationCard,
  getLocationCards,
  getUnbindLocationCards,
  getUnbindUserList,
  generateQRCode
} from "@/api/system/user";
import { getDeptTree, getDeptLazyTree } from "@/api/system/dept";
import { getRoleTree } from "@/api/system/role";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import website from "@/config/website";
import {
  userColumn,
  detailInfoGroup,
  dutyInfoGroup,
  enclosureInfoGroup,
  platformColumn,
  exportColumn
} from "./constant/user.js";
import viewpicture from "../saferisk/components/viewpicture.vue";

export default {
  components: {
    viewpicture
  },
  data() {
    // 密码规则
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };

    // 确认密码规则
    const validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      // 弹窗：查看图片
      localPicBox: false,
      localPictures: [],
      viewPicTitle: "",
      // 左右宽度
      leftWidth: this.$leftWidth,
      rightWidth: this.$rightWidth,
      initFlag: true,
      init: {
        roleTree: [],
        deptTree: []
      },
      // 左侧树
      treeDeptId: "",
      treeData: [],
      treeOption: {
        nodeKey: "id",
        lazy: true,
        treeLoad: function(node, resolve) {
          const parentId = node.level === 0 ? 0 : node.data.id;
          getDeptLazyTree(parentId).then(res => {
            resolve(
              res.data.data.map(item => {
                return {
                  ...item,
                  leaf: !item.hasChildren
                };
              })
            );
          });
        },
        addBtn: false,
        menu: false,
        size: "small",
        props: {
          labelText: "标题",
          label: "title",
          value: "value",
          children: "children"
        }
      },
      // 用户角色配置
      roleBox: false,
      roleGrantList: [],
      roleTreeObj: [],
      props: {
        label: "title",
        value: "key"
      },
      // 用户列表
      form: {},
      search: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 80,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: true,
        viewBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 200,
        column: userColumn,
        group: [
          {
            label: "基础信息",
            prop: "baseInfo",
            icon: "el-icon-user-solid",
            column: [
              {
                label: "登录账号",
                prop: "account",
                span: 24,
                rules: [
                  {
                    required: true,
                    message: "请输入登录账号",
                    trigger: "blur"
                  }
                ]
              },
              {
                label: "密码",
                prop: "password",
                hide: true,
                editDisplay: false,
                viewDisplay: false,
                rules: [
                  {
                    required: true,
                    validator: validatePass,
                    trigger: "blur"
                  }
                ]
              },
              {
                label: "确认密码",
                prop: "password2",
                hide: true,
                editDisplay: false,
                viewDisplay: false,
                rules: [
                  {
                    required: true,
                    validator: validatePass2,
                    trigger: "blur"
                  }
                ]
              }
            ]
          },
          detailInfoGroup,
          dutyInfoGroup,
          enclosureInfoGroup
        ]
      },
      // 平台配置
      platformBox: false,
      platformLoading: false,
      platformQuery: {},
      platformSelectionList: [],
      platformData: [],
      platformForm: {},
      platformPage: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      platformOption: {
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: true,
        viewBtn: true,
        dialogClickModal: false,
        menuWidth: 120,
        editBtnText: "配置",
        column: platformColumn
      },
      // 导入
      excelBox: false,
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: exportColumn
      },
      dialogType: "",
      downloadHead: "/api/fileManager/download/",
      SetHeaders: { "Blade-Auth": getToken() },
      // 照片
      zpFileList: [],
      // 学历证书
      xlzsFileList: [],
      // 附件
      fjFileList: [],
      // 工作简历
      gzjlFileList: [],
      // 弹窗：绑定工卡
      bindLocationCardDialog: false,
      selectedId: "",
      bindForm: {
        gk: ""
      },
      bindRules: {
        gk: [{ required: true, message: "请选择工卡", trigger: "change" }]
      },
      locationCards: [],
      locationCardObj: {},
      // 人员状态对象
      ryztObj: {
        0: "离职",
        1: "在职"
      }
    };
  },
  watch: {
    "form.tenantId"() {
      if (this.form.tenantId !== "" && this.initFlag) {
        this.initData(this.form.tenantId);
      }
    }
  },
  computed: {
    ...mapGetters(["userInfo", "permission"]),

    // 用户列表按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.user_add, false),
        viewBtn: this.vaildData(this.permission.user_view, false),
        delBtn: this.vaildData(this.permission.user_delete, false),
        editBtn: this.vaildData(this.permission.user_edit, false)
      };
    },

    // 用户平台配置列表按钮权限
    platformPermissionList() {
      return {
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtn: this.vaildData(this.permission.user_edit, false)
      };
    },

    // 用户列表勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  mounted() {
    // 非租户模式默认加载管理组数据
    // if (!website.tenantMode) {
    //   this.initData(website.tenantId);
    // }
    this.initData(website.tenantId);
    this.getLocationCardInfo();
  },
  methods: {
    // 点击左侧树
    nodeClick(data) {
      this.treeDeptId = data.id;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },

    // 获取定位卡信息
    getLocationCardInfo() {
      getLocationCards().then(res => {
        this.locationCardObj = {};
        res.data.forEach(item => {
          this.locationCardObj[item.id] = item.bqh;
        });
      });
    },

    // 初始化数据
    initData(tenantId) {
      getRoleTree(tenantId).then(res => {
        const column = this.findObject(this.option.group, "roleId");
        column.dicData = res.data.data;
      });
      getDeptTree(tenantId).then(res => {
        const column = this.findObject(this.option.group, "deptId");
        column.dicData = res.data.data;
      });
    },

    // 确定角色配置
    submitRole() {
      const roleList = this.$refs.treeRole.getCheckedKeys().join(",");
      grant(this.ids, roleList).then(() => {
        this.roleBox = false;
        this.$message.success("操作成功!");
        this.onLoad(this.page);
      });
    },

    // 新增用户
    rowSave(row, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.roleId = row.roleId.join(",");
      add(row).then(
        () => {
          this.initFlag = false;
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },

    // 编辑用户
    rowUpdate(row, index, done, loading) {
      for (let key in row) {
        if (key.indexOf("$") >= 0) {
          delete row[key];
        }
      }
      row.roleId = row.roleId.join(",");
      update(row).then(
        () => {
          this.initFlag = false;
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },

    // 删除一条用户
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
        });
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.treeDeptId = "";
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选用户
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选用户
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 删除多条用户
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message.success("操作成功!");
          this.$refs.crud.toggleSelection();
        });
    },

    // 点击密码重置按钮
    handleReset() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择账号密码重置为123456?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return resetPassword(this.ids);
        })
        .then(() => {
          this.$message.success("操作成功!");
          this.$refs.crud.toggleSelection();
        });
    },

    // 点击角色配置按钮
    handleGrant() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.roleTreeObj = [];
      if (this.selectionList.length === 1) {
        this.roleTreeObj = this.selectionList[0].roleId.split(",");
      }
      getRoleTree().then(res => {
        this.roleGrantList = res.data.data;
        this.roleBox = true;
      });
    },

    // 点击平台配置按钮
    handlePlatform() {
      this.platformBox = true;
    },

    // 点击导入按钮
    handleImport() {
      this.excelBox = true;
    },

    // 导入角色文件后
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.excelBox = false;
      this.refreshChange();
      done();
    },

    // 点击导出按钮
    handleExport() {
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let account = this.query.account !== undefined && this.query.account !== "" && this.query.account !== null ? this.query.account : "";
        let realName = this.query.realName !== undefined && this.query.realName !== "" && this.query.realName !== null ? this.query.realName : "";
        let postId = this.query.postId !== undefined && this.query.postId !== "" && this.query.postId !== null ? this.query.postId : "";
        let ryzt = this.query.ryzt !== undefined && this.query.ryzt !== "" && this.query.ryzt !== null ? this.query.ryzt : "";
        window.open(
          `/api/blade-user/export-userInfoDetail?${this.website.tokenHeader}=${getToken()}&account=${account}&realName=${realName}&postId=${postId}&ryzt=${ryzt}`
        );
      });
    },

    // 导出用户模板文件
    handleTemplate() {
      let str = this.$UploadUrl + '/hg/file/template/UserInformation.xlsx';
      window.open(str);
    },

    // 打开查看、编辑、新增弹窗前
    beforeOpen(done, type) {
      this.dialogType = type;
      this.zpFileList = [];
      this.xlzsFileList = [];
      this.fjFileList = [];
      this.gzjlFileList = [];
      if (type === "add") {
        getUnbindLocationCards().then(res => {
          let gkColumn = this.findObject(this.option.group[3].column, "gk");
          gkColumn.dicData = res.data;
        });
      } else {
        getUnbindUserList(this.form.id)
          .then(res => {
            let gkColumn = this.findObject(this.option.group[3].column, "gk");
            gkColumn.dicData = res.data;
          })
          .then(() => {
            getUser(this.form.id).then(res => {
              this.form = res.data.data;
              for (let key in this.form.userInfoDetail) {
                if (key !== "id") {
                  this.form[key] = this.form.userInfoDetail[key];
                } else {
                  this.form["detailId"] = this.form.userInfoDetail[key];
                }
              }
              // 所属角色
              if (this.form.hasOwnProperty("roleId")) {
                this.form.roleId = this.form.roleId.split(",");
              }
              // 照片
              if (this.form.photo && this.form.photo.length !== 0) {
                this.form.photo.forEach(item => {
                  this.zpFileList.push({
                    name: item.fileName,
                    response: {
                      code: 200,
                      msg: "操作成功",
                      success: true,
                      data: item
                    }
                  });
                });
              }
              // 学历证书
              if (this.form.diploma && this.form.diploma.length !== 0) {
                this.form.diploma.forEach(item => {
                  this.xlzsFileList.push({
                    name: item.fileName,
                    response: {
                      code: 200,
                      msg: "操作成功",
                      success: true,
                      data: item
                    }
                  });
                });
              }
              // 附件
              if (this.form.annex && this.form.annex.length !== 0) {
                this.form.annex.forEach(item => {
                  this.fjFileList.push({
                    name: item.fileName,
                    response: {
                      code: 200,
                      msg: "操作成功",
                      success: true,
                      data: item
                    }
                  });
                });
              }
              // 工作简历
              if (this.form.resume && this.form.resume.length !== 0) {
                this.form.resume.forEach(item => {
                  this.gzjlFileList.push({
                    name: item.fileName,
                    response: {
                      code: 200,
                      msg: "操作成功",
                      success: true,
                      data: item
                    }
                  });
                });
              }
              delete this.form.userInfoDetail;
            });
          });
      }
      this.initFlag = true;
      done();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 获取用户表数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query),
        this.treeDeptId
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = [];
        data.records.forEach(item => {
          for (let key in item.userInfoDetail) {
            if (key !== "id") {
              item[key] = item.userInfoDetail[key];
            } else {
              item["detailId"] = item.userInfoDetail[key];
            }
          }
          this.data.push(item);
        });
        this.loading = false;
        this.selectionClear();
      });
    },

    // 平台配置更新
    platformRowUpdate(row, index, done, loading) {
      updatePlatform(row.id, row.userType, row.userExt).then(
        () => {
          this.platformOnLoad(this.platformPage);
          this.$message.success("操作成功!");
          done();
        },
        error => {
          window.console.log(error);
          loading();
        }
      );
    },

    // 打开平台配置查看、编辑、新增弹窗前
    platformBeforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getUserPlatform(this.platformForm.id).then(res => {
          this.platformForm = res.data.data;
        });
      }
      done();
    },

    // 平台配置清空搜索条件
    platformSearchReset() {
      this.platformQuery = {};
      this.platformOnLoad(this.platformPage);
    },

    // 平台配置搜索条件改变事件
    platformSearchChange(params, done) {
      this.platformQuery = params;
      this.platformPage.currentPage = 1;
      this.platformOnLoad(this.platformPage, params);
      done();
    },

    // 平台配置勾选
    platformSelectionChange(list) {
      this.platformSelectionList = list;
    },

    // 平台配置清空勾选
    platformSelectionClear() {
      this.platformSelectionList = [];
      this.$refs.platformCrud.toggleSelection();
    },

    // 平台配置更换页数
    platformCurrentChange(currentPage) {
      this.platformPage.currentPage = currentPage;
    },

    // 平台配置更换每页显示数量
    platformSizeChange(pageSize) {
      this.platformPage.pageSize = pageSize;
    },

    // 凭条配置刷新
    platformRefreshChange() {
      this.platformOnLoad(this.platformPage, this.platformQuery);
    },

    // 获取平台配置表内容
    platformOnLoad(page, params = {}) {
      this.platformLoading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query),
        this.treeDeptId
      ).then(res => {
        const data = res.data.data;
        this.platformPage.total = data.total;
        this.platformData = data.records;
        this.platformLoading = false;
        this.selectionClear();
      });
    },

    /**
     * 弹窗：图片
     */

    // 点击照片列表中已上传的照片
    previewZP(file) {
      if (
        file.response &&
        file.response.code === 200 &&
        file.response.data &&
        file.response.data.fileUrl
      ) {
        this.localPictures = [file.response.data];
        this.localPicBox = true;
        this.viewPicTitle = "证件照";
      }
    },

    // 点击学历证书列表中已上传的学历证书
    previewXLZS(file) {
      if (
        file.response &&
        file.response.code === 200 &&
        file.response.data &&
        file.response.data.fileUrl
      ) {
        this.localPictures = [file.response.data];
        this.localPicBox = true;
        this.viewPicTitle = "学历证书";
      }
    },

    // 确认照片
    confirmViewPicture() {
      this.localPictures = [];
      this.localPicBox = false;
      this.viewPicTitle = "";
    },

    // 关闭弹窗
    handleClosePicBox() {
      this.confirmViewPicture();
    },

    // 点击导出个人档案按钮
    handleExportArchives() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定导出选择用户个人档案?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // window.open(
        //   `/api/blade-user/export-user?${this.website.tokenHeader}=${getToken()}&account=${account}`
        // );
      });
    },

    // 点击离职按钮
    handleLeaveJob() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择用户设为离职?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        updateUserStatus(this.ids, 0).then(res => {
          if (res.data.success) {
            this.$message.success("操作成功!");
            this.page.currentPage = 1;
            this.onLoad(this.page);
          }
        });
      });
    },

    // 点击恢复按钮
    handleRefreshJob() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择用户设为在职?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        updateUserStatus(this.ids, 1).then(res => {
          if (res.data.success) {
            this.$message.success("操作成功!");
            this.page.currentPage = 1;
            this.onLoad(this.page);
          }
        });
      });
    },

    /**
     * 上传照片
     */

    // 上传照片前
    beforeUploadZP(file) {
      console.log(file);
      var isLimit = this.zpFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一张照片!");
      }
      return isLimit;
    },

    // 上传照片成功
    uploadZPSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.zpFileList = fileList;
      this.form.zp = response.data.id;
    },

    // 删除照片
    handleRemoveZP(index) {
      this.zpFileList.splice(index, 1);
      this.form.zp = "";
    },

    /**
     * 上传学历证书
     */

    // 上传学历证书前
    beforeUploadXLZS(file) {
      console.log(file);
      var isLimit = this.xlzsFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一张学历证书!");
      }
      return isLimit;
    },

    // 上传学历证书成功
    uploadXLZSSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.xlzsFileList = fileList;
      this.form.xlzs = response.data.id;
    },

    // 删除学历证书
    handleRemoveXLZS(index) {
      this.xlzsFileList.splice(index, 1);
      this.form.xlzs = "";
    },

    /**
     * 上传附件
     */

    // 上传附件前
    beforeUploadFJ(file) {
      console.log(file);
      var isLimit = this.fjFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个附件!");
      }
      return isLimit;
    },

    // 上传附件成功
    uploadFJSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.fjFileList = fileList;
      this.form.fj = response.data.id;
    },

    // 删除附件
    handleRemoveFJ(file, fileList) {
      this.fjFileList = fileList;
      this.form.fj = "";
    },

    /**
     * 上传工作简历
     */

    // 上传工作简历前
    beforeUploadGZJL(file) {
      console.log(file);
      var isLimit = this.gzjlFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个工作简历!");
      }
      return isLimit;
    },

    // 上传工作简历成功
    uploadGZJLSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.gzjlFileList = fileList;
      this.form.gzjl2 = response.data.id;
    },

    // 删除工作简历
    handleRemoveGZJL(file, fileList) {
      this.gzjlFileList = fileList;
      this.form.gzjl2 = "";
    },

    /**
     * 弹窗：绑定工卡
     */

    // 打开绑定工卡弹窗
    handleBindGK(id) {
      getUnbindLocationCards()
        .then(res => {
          this.locationCards = res.data;
        })
        .then(() => {
          this.selectedId = id;
          this.bindLocationCardDialog = true;
        });
    },

    // 取消、关闭绑定工卡弹窗
    closeBindLocationCardDialog() {
      this.bindLocationCardDialog = false;
      this.selectedId = "";
      this.bindForm = {
        gk: ""
      };
    },

    // 绑定工卡
    bindLocationCard() {
      this.$refs["bindForm"].validate(valid => {
        if (valid) {
          bindLocationCard(this.selectedId, this.bindForm.gk).then(res => {
            if (res.data.success) {
              this.closeBindLocationCardDialog();
              this.page.currentPage = 1;
              this.onLoad(this.page);
            }
          });
        }
      });
    },

    /**
     * 二维码
     */

    // 生成二维码
    generateQRCode(id) {
      this.$confirm("确定将选择用户生成二维码?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        generateQRCode(id).then(res => {
          if (res.data.success) {
            this.$message.success("二维码生成成功!");
            this.page.currentPage = 1;
            this.onLoad(this.page);
          }
        });
      });
    },

    // 查看二维码
    handleViewQRCode(row) {
      getUser(row.id).then(res => {
        var resData = res.data.data;
        if (res.data.success && resData.qrCode && resData.qrCode.fileUrl) {
          this.localPictures = [resData.qrCode];
          this.localPicBox = true;
          this.viewPicTitle = "二维码";
        }
      });
    }
  }
};
</script>

<style lang="scss">
.userManage {
  .el-scrollbar__wrap {
    margin-left: 0px !important;
    margin-right: 0px !important;
  }
}

.zp_content,
.xlzs_content {
  .el-upload-list {
    display: none;
  }

  .el-tag {
    .el-icon-close {
      top: -84px;
    }
  }
}

.bind_gk_form {
  .el-form-item__content {
    .el-form-item__error {
      margin-left: 65px;
    }
  }
}
</style>

<style lang="scss" scoped>
.el-row {
  height: calc(100% - 10px);
}

.el-col {
  height: 100%;
}

.box {
  height: 100%;
  margin-bottom: 0;
  margin-right: $common_margin_right;
}

.zp_content,
.xlzs_content {
  .el-upload-list__item {
    display: none !important;
  }

  .el-tag {
    height: 100px;
    line-height: 100px;
    padding: 0px 10px 0px 0px;
    margin-left: 0px;
    margin-top: 10px;
  }

  img {
    width: 98px;
    height: 98px;
    cursor: pointer;
  }
}

.bind_card_footer {
  text-align: center;
  margin-top: 15px;

  .el-button {
    width: 100px;
    height: 35px;
  }
}

.gk_select {
  width: calc(100% - 80px);
}
</style>